package com.cloud.Service.impl;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： linJianHong
 * @dateTime： 17:40 2022/4/29
 * @Description: Information determination
 * @ClassName: UserDetailsServiceImpl
 */

import com.cloud.dao.PermissionsDao;
import com.cloud.dao.UserInfoDao;
import com.cloud.domain.LoginUser;
import com.cloud.domain.User;
import com.cloud.pojo.UserInfo;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserInfoDao userInfoDao;

    @Resource
    PermissionsDao permissionsDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = null;
        System.out.println(username);
        if(username.length() < 12)
            //如果没有查询到用户就抛出异常
            user = userInfoDao.loginByPhoneNumber(new UserInfo().setPhoneNumber(username));
        else{
            System.out.println(username);
            user = userInfoDao.loginByCardId(new UserInfo().setUserId(username));
        }

        System.out.println(user);

        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }

        List<String> list = permissionsDao.getPermissions(user.getType());
//        把数据封装成UserDetails返回
        return new LoginUser(user,list);
    }
}
